﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Com.Seezt.Skins;
using Components.Enum;
using UI.Lib;
using System.Collections;
using Components;
using UI.Lib.Factory;
using Controls;

namespace UI.ParentForm
{
    public partial class BaseEdit : BaseForm
    {
        protected string key;
        protected int saveSuccessCount = 0; //新增的时候，模式是不关闭新增页面继续给用户编辑的，但是如果新增后点击关闭按钮，Main页面不会自动刷新

        private string _saveCallFuntion;

        //加载完成后是否最大化的标识
        protected bool MaxStateFlag = false;

        protected bool IsAlertInDelete = true;

        /// <summary>
        /// 用于子页面控制程序是否继续保存的开关
        /// </summary>
        protected bool hasError = false;

        /// <summary>
        /// 是否为用户关闭窗口
        /// </summary>
        private bool _isUserCloseWin = true;

        /// <summary>
        /// 保存时候调用的方法 , 类名$方法名，方法必须返回String,参数为Hashtable
        /// </summary>
        public string SaveCallFuntion
        {
            get { return _saveCallFuntion; }
            set { _saveCallFuntion = value; }
        }

        protected bool IsAfterSaveCloseWin = true;

        //保存后，是否刷新父级窗口
        protected bool IsReloadAfterSave = true;

        public bool IsReload
        {
            get { return IsReloadAfterSave; }
        }

        #region 属性
        /// <summary>
        /// 是否需要加载控件设计
        /// </summary>
        protected bool isNeedControl = true;

        private bool _isAutoCheck = true;

        /// <summary>
        /// 是否自动验证Table
        /// </summary>
        public bool IsAutoCheck
        {
            get { return _isAutoCheck; }
            set { _isAutoCheck = value; }
        }

        #endregion

        public BaseEdit()
        {
            InitializeComponent();
            if (!isDebug)
            {
                _pageInit();
                PageInit();//初始化方法
                InitControl();// 加载控件设计
            }
        }

        public BaseEdit(string action)
            : this()
        {
            this.Action = action;
        }

        /// <summary>
        /// 加载控件设计
        /// </summary>
        private void InitControl()
        {
            if (!isNeedControl) //不加载数据库的字段设计
            {
                this.tbSummary.Visible = false;
                return;
            }

            string page = this.GetType().FullName;

            //加载页面概要设计信息
            CommonObject obj = PageCache.GetSys5A00(page, PageControlType.SummaryCtl);
            if (obj.IsEmptyData) return; //页面未设置概要信息
            int colsize = Convert.ToInt32(obj.GetValue("colsize"));
            string text = Validation.ToString(obj.GetValue("remark"));
            this.scrollBar1.Text = string.IsNullOrEmpty(text) ? Global.SummaryHelpText : text;

            //加载页面控件数据设计
            DataTable dt = PageCache.GetLayout(page, PageControlType.SummaryCtl);

            if (null == dt || 0 == dt.Rows.Count) return;

            tbSummary.DataSource = dt;
            tbSummary.AutoHeight = true;
            tbSummary.ColSize = colsize;
            tbSummary.Bind();
        }

        #region 抽象的虚方法

        //初始化方法
        protected virtual void PageInit()
        { }

        #endregion

        private void tspBtnClose_Click(object sender, EventArgs e)
        {
            IsReloadAfterSave = saveSuccessCount > 0;
            this.Close();
        }

        private void tspBtnSave_Click(object sender, EventArgs e)
        {
            if (IsAlertInDelete && "D" == this.Action)
            {
                if (MsgBox.Show(this, "提示", "删除后将不能恢复，是否确定删除？", MessageBoxButtons.YesNo) == DialogResult.No)
                    return;
            }

            SaveData();
        }

        //回写方法
        protected virtual void SaveData()
        {
            if (_isAutoCheck && !AutoCheck()) return; //自动验证不通过
            if (!Check()) return; //手工验证失败

            if (!this.tbSummary.IsModify() && "D" != this.Action)
            {
                MsgBox.Show(this, "当前页面数据未发生改变，无需保存！");
                return;
            }

            Hashtable data = this.tbSummary.GetAllValue();
            //除了表格控件中的值，也许客户端还需要保存其他的值到服务器端，如果Hashtable中的键和表格中的冲突了，以本次设置为准
            Hashtable otherdb = this.SaveOtherData();
            if (hasError) return;
            // 将子页面中返回的数据和表格控件中的数据合并生成jSON字符串，返回服务器处理
            string json = StringUtil.Entity.MergeToJson(true, data, otherdb);

            if (string.IsNullOrEmpty(this.SaveCallFuntion)) return;

            string errmsg = CommonHelper.Entity.Save(SaveCallFuntion, json, this.Action); //调用服务器的保存方法

            bool isSuccess = string.IsNullOrEmpty(errmsg); // 是否保存成功
            if (!isSuccess) MsgBox.ShowErrorMsg(this, errmsg);
            else
            {
                MsgBox.Show(this, "数据保存成功！");
                saveSuccessCount++;

                if (!IsAfterSaveCloseWin) //保存后如果不关闭窗口的话，则清空界面
                {
                    this.tbSummary.Clear();
                    this.tbSummary.Focus();
                    this.tbSummary.FocusFirst();
                }
            }
            //保存后调用
            AfterSaveData(isSuccess);

            if (IsAfterSaveCloseWin) //保存后自动关闭窗口
            {
                _isUserCloseWin = false;
                this.Close();
            }

            this.tbSummary.SaveBak();
        }

        private void _pageInit()
        {
            //this.BackColor = Color.FromArgb(236, 241, 245);
        }

        /// <summary>
        /// 自动验证
        /// </summary>
        /// <returns></returns>
        protected bool AutoCheck()
        {
            string errmsg = this.tbSummary.CheckSelf();
            bool rlt = string.IsNullOrEmpty(errmsg);
            if (rlt == false)
            {
                MessageBox.Show(errmsg, "提示");
                return false;
            }

            return true;
        }

        /// <summary>
        /// 保存后调用
        /// </summary>
        /// <param name="isSuccess"></param>
        protected virtual void AfterSaveData(bool isSuccess) { }

        /// <summary>
        /// 手工验证
        /// </summary>
        /// <returns></returns>
        protected virtual bool Check() { return true; }

        /// <summary>
        /// 除了表格控件中的值，也许客户端还需要保存其他的值到服务器端，如果Hashtable中的键和表格中的冲突了，以本次设置为准
        /// </summary>
        /// <returns></returns>
        protected virtual Hashtable SaveOtherData() { return null; }

        /// <summary>
        /// 自动加载页面数据
        /// </summary>
        /// <returns></returns>
        protected virtual DataRow LoadEditData(string action, string where)
        {
            action = string.IsNullOrEmpty(action) ? "E" : action; //设置默认的Action

            DataTable data = CommonHelper.Entity.LoadEditData(this.GetType().FullName, action, "Summary", where);
            if (data == null || data.Rows.Count == 0) return null;

            this.tbSummary.Fill(data); //设置页面控件的值
            this.tbSummary.SaveBak();

            return data.Rows[0]; //可能子页面中还会有用
        }

        /// <summary>
        /// 根据当前状态，充值页面控件状态
        /// </summary>
        protected void RefreshControl()
        {
            this.tbSummary.SetControlState(this.Action);
        }

        /// <summary>
        /// 页面加载完成后，自动重置一次控件状态
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if ("V" == this.Action) //显示状态下不显示保存按钮
            {
                tspBtnSave.Visible = false;
            }

            if (MaxStateFlag)
            {
                this.WindowState = FormWindowState.Maximized;
            }

            this.RefreshControl();
            AfterSystemChangeControlState();
            this.tbSummary.FormatStyle();
            this.tbSummary.SaveBak(); //保存当前数据，用于做是否修改的提示

            _SetFontSize();
            _SetToolBtnStyle();
            _SetPanelLocation();
            isLoadOk = true;
        }

        /// <summary>
        /// 当页面上系统设置完控件状态后执行
        /// </summary>
        protected virtual void AfterSystemChangeControlState() { }

        /// <summary>
        /// 创建完控件后执行（添加属性）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected virtual void tbSummary_AfterCreateControl(object sender, Controls.Args.SummaryArgs e)
        {
            Control c = sender as Control;
            if (c == null) return;

            //添加默认事件
            AddEvent(c);

            //调用系统的创建控件
            AfterSummaryCreateControl(c.Name, c, e);
        }

        protected virtual void AfterSummaryCreateControl(string colName, Control c, Controls.Args.SummaryArgs e) { }

        protected override void AfterSummaryPopUp(PsPopWin popTarget, Hashtable hs, bool clearFlag, string status)
        {
            if (null == hs || 0 == hs.Count) return;

            Control c = null;
            PsPopWin pop = null;
            string key = "";
            string value = "";
            bool isAlert = false;
            foreach (DictionaryEntry entry in hs)
            {
                key = entry.Key.ToString();
                value = (null == entry.Value || clearFlag) ? "" : entry.Value.ToString();
                if (key == "$SELF$")
                {
                    popTarget.Text = popTarget.Value = value;
                    if (!string.IsNullOrEmpty(value))
                    {
                        popTarget.PressWord = null;
                    }
                    if (!clearFlag && string.IsNullOrEmpty(value))
                    {
                        isAlert = true; //给出提示
                    }
                }
                else if (key.IndexOf("$VALUE$") > -1)//准备将值写入弹出框份额Value内
                {
                    if (key.IndexOf("&") > -1)//准备将值写入其他弹出框份额Value内
                    {
                        string name = key.Replace("$VALUE$&", "");
                        if (!this.tbSummary.Controls.ContainsKey(name)) continue;

                        pop = this.tbSummary.Controls[name] as PsPopWin;
                        if (pop == c) continue;

                        pop.Value = value;
                    }
                    else
                    {
                        popTarget.Value = value;
                    }
                }
                else
                {
                    this.tbSummary.SetValue(key, value);
                }
            }

            if (isAlert && "M" != status)
            {
                popwin_MouseDoubleClick(popTarget, null);
                //MessageBox.Show(string.Format("[{0}]未选择有效的值！", popTarget.Lable), "提示");
            }
        }

        #region 热键相关

        private void Form_Activated(object sender, EventArgs e)
        {
        }

        private void Form_Leave(object sender, EventArgs e)
        {
        }

        public override bool BeforePopWin(string name, ref string where, ref string[] others)
        {
            return base.BeforePopWin(name, ref where, ref others);
        }

        public override void AfterPopWin(string name, Hashtable data, bool ischange)
        {
            base.AfterPopWin(name, data, ischange);
        }

        #endregion

        void _SetFontSize()
        {
            this.AutoScaleMode = AutoScaleMode.None;
            this.tbSummary.Font = this.tspTop.Font = this.scrollBar1.Font = Global.AllFont;

            this.tbSummary.BackColor = this.scrollBar1.BackColor = Global.AllBGColor;
        }

        private void BaseEdit_FormClosing(object sender, FormClosingEventArgs e)
        {
            bool isExit = null != Context.GetValueByKey("EXIT");

            if (!isExit)
            {
                if (_isUserCloseWin && this.tbSummary.IsModify() &&
                    MessageBox.Show("界面数据已经改变，是否真要退出？", "提示", MessageBoxButtons.YesNo)
                        != DialogResult.Yes)
                {
                    e.Cancel = true;
                }

                IsReloadAfterSave = saveSuccessCount > 0;
            }
        }

        private void BaseEdit_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.F8:    //按下的是Insert
                    if (CanClickButton(this.tspBtnSave)) tspBtnSave_Click(this.tspBtnSave, null);
                    break;
                case Keys.PageUp:    //按下的是page up，Id号为106 == 返回及关闭
                    this.Close();
                    break;
                case Keys.F4:    //按下的是F4，Id号为107 == 返回及关闭
                    this.Close();
                    break;
                case Keys.F5:    //按下的是F5，Id号为108 == 调用子菜单
                    break;
            }
        }

        private void scrollBar1_Enter(object sender, EventArgs e)
        {
            SendKeys.Send("{TAB}"); //让滚动栏不获得焦点
        }

        void _SetToolBtnStyle()
        {
            ToolStripButton btn = null;
            foreach (ToolStripItem item in this.tspTop.Items)
            {
                if (item is ToolStripButton)
                {
                    btn = item as ToolStripButton;
                    btn.BackgroundImage = base.Imgs.Images[3];
                }
            }
        }

        private void BaseEdit_ClientSizeChanged(object sender, EventArgs e)
        {
            _SetPanelLocation();
        }

        void _SetPanelLocation()
        {
            this.tbSummary.Height = this.Height - this.scrollBar1.Height - 90;
            this.panel1.Location = new Point(this.tbSummary.Location.X + this.tbSummary.Width, this.tbSummary.Location.Y);
            this.panel1.Size = new Size(50, this.tbSummary.ClientSize.Height);

            this.scrollBar1.Location = new Point(this.tbSummary.Location.X, this.scrollBar1.Location.Y);
            this.scrollBar1.Size = new Size(tbSummary.Width + 50, this.scrollBar1.Height);
        }
    }
}
